package top.v5it.japi.plus.spring.boot.autoconfigure;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import top.v5it.japi.plus.core.spring.web.JapiXssFilter;
import top.v5it.japi.plus.spring.boot.autoconfigure.properties.JapiProperties;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 开启XSS防护
 *
 * @author zhanpu
 * @date 2020-11-20
 */
@Slf4j
@ConditionalOnWebApplication
@ConditionalOnProperty(name = "spring.japi.xss.enabled", havingValue = "true")
public class JapiXssFilterConfiguration {

    /**
     * xss过滤拦截器
     *
     * @param japiProperties {@link JapiProperties}
     * @return {@link FilterRegistrationBean}
     */
    @Bean
    @ConditionalOnMissingBean
    public FilterRegistrationBean<JapiXssFilter> xssFilterRegistrationBean(JapiProperties japiProperties) {
        log.info(">>>>>>>>>>[Init FilterRegistrationBean]<<<<<<<<<<");

        JapiProperties.Xss xss = japiProperties.getXss();
        FilterRegistrationBean<JapiXssFilter> filterRegistry = new FilterRegistrationBean<>();
        filterRegistry.setFilter(new JapiXssFilter());
        filterRegistry.setOrder(1);
        filterRegistry.setEnabled(true);
        filterRegistry.addUrlPatterns(xss.getIncludes());

        Map<String, String> initParameters = new HashMap<>(2);
        initParameters.put(JapiXssFilter.INIT_PARAMETER_NAME_EXCLUDES, xss.getExclude());
        initParameters.put(JapiXssFilter.INIT_PARAMETER_NAME_IS_INCLUDE_RICH_TEXT, Objects.toString(xss.isIncludeRichText()));
        filterRegistry.setInitParameters(initParameters);

        return filterRegistry;
    }
}
